package com.zunipe.accounts.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.zunipe.accounts.AccountApplication;
import com.zunipe.accounts.LoginActivity;
import com.zunipe.accounts.databinding.FragmentPersonalBinding;

public class PersonalFragment extends Fragment {
    FragmentPersonalBinding binding;
    private ActivityResultLauncher<Intent> launcher;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentPersonalBinding.inflate(inflater, container, false);
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> update());
        update();
        binding.btnLogout.setOnClickListener(v -> {
            AccountApplication.getInstance().logout();
            Intent intent = new Intent();
            intent.setAction("com.zunipe.accounts.update.list");
            intent.setPackage("com.zunipe.accounts");
            requireActivity().sendBroadcast(intent);
            update();
        });
        return binding.getRoot();
    }

    private void update() {
        if (!AccountApplication.getInstance().isLogin()) {
            binding.tvUsername.setText("立即登录");
            binding.btnLogout.setVisibility(View.INVISIBLE);
            binding.tvUsername.setOnClickListener(v -> {
                Intent intent = new Intent(requireContext(), LoginActivity.class);
                launcher.launch(intent);
            });
        } else {
            binding.tvUsername.setText("欢迎回来！" + AccountApplication.getInstance().getUsername());
            binding.tvUsername.setOnClickListener(null);
            binding.btnLogout.setVisibility(View.VISIBLE);
        }
    }
}
